import { setToken, removeToken } from '@/utils/auth'
import router from '../../router'

const getUserInfo = () => {
  const random = Math.random()
  return {
    name: random > 0.5 ? '超级管理员' : '普通管理员',
    roles: random > 0.5 ? ['admin'] : ['admin'],
    token: 'sldkfhs892347293kfa234slkdh'
  }
}

const login = () => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(getUserInfo())
    }, 1000)
  })
}

const initialState = {
  token: '',
  userInfo: null
}

export default {
  namespaced: true,
  state: Object.assign({}, initialState),
  mutations: {
    SET_TOKEN(state, token) {
      state.token = token
    },
    SET_USER_INFO(state, userInfo) {
      state.userInfo = userInfo
    },
    RESET_USER_INFO(state) {
      Object.keys(initialState).forEach((key) => {
        state[key] = initialState[key]
      })
    }
  },
  actions: {
    // 登录
    login({ commit }, form) {
      return login(form).then((res) => {
        setToken(res.token)
        commit('SET_TOKEN', res.token)
        // commit('SET_USER_INFO', res)
        return res
      })
    },
    // 获取用户信息
    getUserInfo({ commit }) {
      return new Promise((resolve) => {
        const userInfo = getUserInfo()
        commit('SET_TOKEN', userInfo.token)
        commit('SET_USER_INFO', userInfo)
        resolve(userInfo)
      })
    },
    // 退出登录
    logout({ dispatch, commit }) {
      removeToken()
      commit('RESET_USER_INFO') // 重置用户信息
      dispatch('permission/resetRoutes', null, { root: true }) // 重置路由
      dispatch('tagsView/delAllTag', null, { root: true }) // 重置标签
      router.push('/login')
    }
  }
}
